package com.xinchuang.service.targetSystem.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xinchuang.common.*;
import com.xinchuang.entity.target.TargetSpecialAttribute;
import com.xinchuang.entity.targetSystem.RangeType;
import com.xinchuang.entity.targetSystem.system.*;
import com.xinchuang.mapper.targetSystem.TargetMapper;
import com.xinchuang.mapper.targetSystem.TargetSubTypeMapper;
import com.xinchuang.mapper.targetSystem.TargetTypeMapper;
import com.xinchuang.mapper.targetSystem.ZoneMapper;
import com.xinchuang.entity.targetSystem.object.SpecialAdd;
import com.xinchuang.pojoUtil.TargetUtil;
import com.xinchuang.service.target.TargetSpecialAttributeService;
import com.xinchuang.service.targetSystem.TargetTypeService;
import com.xinchuang.service.targetSystem.target.PostureAttributeService;
import com.xinchuang.service.targetSystem.target.PostureTypeService;
import com.xinchuang.util.FileElseUtil;
import com.xinchuang.util.SnowflakeIdWorker;
import com.xinchuang.utils.MyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.json.JsonArray;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName TargetTypeServiceImpl
 * @Description: TODO(目标类别服务实现)
 * @Author zhangxuan
 * @Date 2021-03-31 15:57
 * @Verion V1.0
 */
@Slf4j
@Service(value = "targetTypeService")
public class TargetTypeServiceImpl implements TargetTypeService {

    @Resource
    private TargetTypeMapper targetTypeMapper;

    @Resource
    private TargetMapper targetMapper;

    @Resource
    private ZoneMapper zoneMapper;

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private Element element;

    @Resource
    private TargetSubTypeMapper targetSubTypeMapper;

    @Resource
    private PostureTypeService postureTypeService;

    @Resource
    private PostureAttributeService postureAttributeService;

    @Resource
    private TargetSpecialAttributeService targetSpecialAttributeService;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);

    @Override
    public void initialize() {
        TargetType targetType = new TargetType();
        targetType.setTypeId("1");
        targetType.setParentId("0");
        targetType.setTypeName(keyWordSystem.getSYSTEM_NAME());
        targetType.setLevel("0");
        targetTypeMapper.addUpdateType(targetType);
        PostureType postureType = new PostureType();
        postureType.setTypeId("1");
        postureType.setParentId("0");
        postureType.setTypeName(keyWordSystem.getSYSTEM_NAME());
        postureType.setLevel("0");
        postureTypeService.saveOrUpdate(postureType);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public synchronized Result addTargetType(TargetType targetType) {
        List<String> targetNames = null;
        if ("1".equals(targetType.getLevel())) {
            targetNames = targetTypeMapper.findTargetNameByLevel(targetType.getLevel());
        } else {
            targetNames = targetTypeMapper.findTargetNameByLevelAndParantId(targetType.getLevel(), targetType.getParentId());
        }
        if (null != targetNames && !targetNames.isEmpty()) {
            for (String targetName : targetNames) {
                if (targetName.equals(targetType.getTypeName())) {
                    return ResultUtil.error(ResultEnum.TARGET_TYPE_NAME_EXIST);
                }
            }
        }
        targetType.setTypeId(snowflakeIdWorker.nextId() + "");
        Integer count = targetTypeMapper.selectSpecialCount(targetType.getParentId());
        if (null == count) {
            targetType.setSort(1);
        } else {
            targetType.setSort(count + 1);
        }
        targetTypeMapper.addType(targetType);
        targetTypeMapper.addSign(targetType.getTypeId(), "default.png");
        return ResultUtil.success("新增成功", null);
    }

    @Override
    public Result delTargetType(String typeId) {
        if (StringUtils.isBlank(typeId)) {
            return ResultUtil.success("删除成功", null);
        }
        if (typeId.equals("1")) {
            return ResultUtil.error(ResultEnum.TARGET_TYPE_PARENT_NOT_DEL);
        }
        targetTypeMapper.delType(typeId);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result updateTargetType(TargetType targetType) {
        if (targetType.getTypeId().equals("1")) {
            return ResultUtil.error(ResultEnum.TARGET_TYPE_PARENT_UPDATE);
        }
        if (!targetType.getLevel().equals("1") && !targetType.getLevel().equals("2")) {
            return ResultUtil.error(ResultEnum.PARENT_ERROR);
        }
        List<TargetType> targetNames = null;
        if (targetType.getLevel().equals("1")) {
            targetNames = targetTypeMapper.findTargetTypeByLevel(targetType.getLevel());
        } else {
            targetNames = targetTypeMapper.findTargetTypeByLevelAndParantId(targetType.getLevel(), targetType.getParentId());
        }
        if (null != targetNames && !targetNames.isEmpty()) {
            for (TargetType type : targetNames) {
                if (!type.getTypeId().equals(targetType.getTypeId()) && type.getTypeName().equals(targetType.getTypeName())) {
                    return ResultUtil.error(ResultEnum.TARGET_TYPE_NAME_EXIST);
                }
            }
        }
        targetTypeMapper.updateType(targetType);
        return ResultUtil.success("更新成功", null);
    }

    @Override
    public Result<List<Map<String, Object>>> selectTargettype() {
        List<TargetType> list = targetTypeMapper.findAll();
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.success("查询成功", new ArrayList<>());
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> parent = new HashMap<>();
        parent.put("typeId", "1");
        parent.put("typeName", keyWordSystem.getSYSTEM_NAME());
        parent.put("level", "0");
        parent.put("sign", 0);
        parent.put("url", null);
        parent.put("children", getTreeChild("1", list));
        resultList.add(parent);
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    public Result<List<Map<String, Object>>> selectTargetAndSubTypeTree() {
        List<TargetType> list = targetTypeMapper.findAll();
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.success("查询成功", new ArrayList<>());
        }
        List<TargetSubType> subTypes = targetSubTypeMapper.selectList(null);
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> parent = new HashMap<>();
        parent.put("typeId", "1");
        parent.put("typeName", keyWordSystem.getSYSTEM_NAME());
        parent.put("level", "0");
        parent.put("sign", 0);
        parent.put("url", null);
        parent.put("children", getTargetAndSubTree("1", list, subTypes));
        resultList.add(parent);
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public synchronized Result addPostureType(PostureType postureType) {
        //验证类型名称重复
        Integer count;
        if ("1".equals(postureType.getLevel())) {
            count = postureTypeService.lambdaQuery()
                    .eq(PostureType::getLevel, 1)
                    .eq(PostureType::getTypeName, postureType.getTypeName().trim())
                    .count();
        } else {
            count = postureTypeService.lambdaQuery()
                    .eq(PostureType::getLevel, postureType.getLevel())
                    .eq(PostureType::getTypeName, postureType.getTypeName().trim())
                    .eq(PostureType::getParentId, postureType.getParentId())
                    .count();
        }
        if (null != count && count > 0) {
            return ResultUtil.error(ResultEnum.TARGET_TYPE_NAME_EXIST);
        }
        Integer sortMax = postureTypeService.getTypeMaxSort(postureType.getParentId());
        if (null == sortMax) {
            postureType.setSort(1);
        } else {
            postureType.setSort(sortMax + 1);
        }
        postureType.setTypeName(postureType.getTypeName().trim());
        postureTypeService.save(postureType);
        zoneMapper.addSign(postureType.getTypeId(), "default.png");
        return ResultUtil.success("新增成功", null);
    }

    @Override
    public Result deletePostureType(String typeId) {
        if (StringUtils.isBlank(typeId)) {
            return ResultUtil.success("删除成功", null);
        }
        if (typeId.equals("1")) {
            return ResultUtil.error(ResultEnum.TARGET_TYPE_PARENT_NOT_DEL);
        }
        postureTypeService.removeById(typeId);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result updatePostureType(PostureType postureType) {
        if ("1".equals(postureType.getTypeId())) {
            return ResultUtil.error(ResultEnum.TARGET_TYPE_PARENT_UPDATE);
        } else if (!"1".equals(postureType.getLevel()) && !"2".equals(postureType.getLevel())) {
            return ResultUtil.error(ResultEnum.PARENT_ERROR);
        }
        //名称重复判断
        PostureType count;
        if ("1".equals(postureType.getLevel())) {
            count = postureTypeService.lambdaQuery()
                    .eq(PostureType::getLevel, 1)
                    .eq(PostureType::getTypeName, postureType.getTypeName().trim())
                    .one();
        } else {
            count = postureTypeService.lambdaQuery()
                    .eq(PostureType::getLevel, postureType.getLevel())
                    .eq(PostureType::getTypeName, postureType.getTypeName().trim())
                    .eq(PostureType::getParentId, postureType.getParentId())
                    .one();
        }
        if (ObjectUtil.isNotNull(count) && !count.getTypeId().equals(postureType.getTypeId())) {
            return ResultUtil.error(ResultEnum.TARGET_TYPE_NAME_EXIST);
        }
        postureType.setTypeName(postureType.getTypeName().trim());
        postureTypeService.updateById(postureType);
        return ResultUtil.success("更新成功", null);
    }

    @Override
    public Result selectPostureType() {
        List<PostureType> list = postureTypeService.findAll();
        if (CollectionUtil.isEmpty(list)) {
            return ResultUtil.success("查询成功", new ArrayList<>());
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> parent = new HashMap<>();
        parent.put("typeId", "1");
        parent.put("typeName", keyWordSystem.getSYSTEM_NAME());
        parent.put("level", "0");
        parent.put("sign", 0);
        parent.put("url", null);
        parent.put("children", getPostureTreeChild("1", list));
        resultList.add(parent);
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    public List<Map<String, Object>> selectSystemsTargettype(List<String> typeList) {
        List<TargetType> list = targetTypeMapper.findAll();
        if (null == list || list.isEmpty()) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> parent = new HashMap<>();
        parent.put("typeId", "1");
        parent.put("typeName", keyWordSystem.getSYSTEM_NAME());
        parent.put("level", "0");
        parent.put("sign", "0");
        parent.put("children", getTreeChild("1", list, typeList));
        resultList.add(parent);
        return resultList;
    }

    @Override
    public Result addSpecialAttribute(SpecialAdd specialAdd) {
        if (judgeParamName(specialAdd.getKey())) {
            return ResultUtil.error(500, specialAdd.getKey() + "字段名称是系统专有属性，请重新命名");
        }
        //判断字段名称是否重复
        if (ObjectUtil.isNotEmpty(targetTypeMapper.selectIdByKey(specialAdd.getKey()))) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
        }
        //判断属性名称是否重复
        if (ObjectUtil.isNotEmpty(targetTypeMapper.selectIdByTypeIdAndKeyName(specialAdd.getTypeId(), specialAdd.getKeyName()))) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
        }
        specialAdd.setId(snowflakeIdWorker.nextId() + "");
        SpecialAttribute attribute = FileElseUtil.getSpecialAttributeByAdd(specialAdd);
        Integer maxSort = targetTypeMapper.getSpecialMaxSort(specialAdd.getTypeId());
        if (null == maxSort) {
            maxSort = 0;
        }
        attribute.setSort(maxSort + 1);
        targetTypeMapper.addSpecial(attribute);
        return ResultUtil.success("新增成功", null);
    }

    @Override
    public Result delSpecialAttribute(String id) {
        if (StringUtils.isBlank(id)) {
            return ResultUtil.error(ResultEnum.DELETE_EMPTY);
        }
        SpecialAttribute special = targetTypeMapper.findSpecialById(id);
        if (ObjectUtil.isNotEmpty(special) && special.getTypeId().equals("99001")) {
            return ResultUtil.error(500, "系统默认类型无法删除");
        }
        targetTypeMapper.delSpecial(id);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result updateSpecialAttribute(SpecialAdd specialAdd) {
        if (judgeParamName(specialAdd.getKey())) {
            return ResultUtil.error(500, specialAdd.getKey() + "字段名称是系统专有属性，请重新命名");
        }
        if (specialAdd.getTypeId().equals("99001")) {
            return ResultUtil.error(500, "系统默认类型无法修改");
        }
        TargetSpecialAttribute attribute = targetSpecialAttributeService.getById(specialAdd.getId());
        //字段名称不可修改
        specialAdd.setKey(attribute.getKeyValue());
        /**
        //判断字段名称是否重复
        String id = targetTypeMapper.selectIdByKey(specialAdd.getKey());
        if (ObjectUtil.isNotEmpty(id) && !id.equals(specialAdd.getId())) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
        }**/
        //判断属性名称是否重复
        String id = targetTypeMapper.selectIdByTypeIdAndKeyName(specialAdd.getTypeId(), specialAdd.getKeyName());
        if (ObjectUtil.isNotEmpty(id) && !id.equals(specialAdd.getId())) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
        }
        targetTypeMapper.updateSpecial(FileElseUtil.getSpecialAttributeByAdd(specialAdd));
        return ResultUtil.success("更新成功", null);
    }

    @Override
    public Result selectSpecialAttribute(Integer pageNum, Integer pageSize, String typeId) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(typeId)) {
            resultMap.put("commonList", new ArrayList<>());
            return ResultUtil.success("查询成功", resultMap);
        }
        typeId = TargetUtil.getParamListOrString(typeId);
        if (pageNum == null || pageSize == null) {
            List<SpecialAttribute> list = targetTypeMapper.findSpecialByTypeId(typeId);
            List<Object> lists = new ArrayList<>();
            String typeName = targetTypeMapper.getTypeName(typeId);
            lists.addAll(FileElseUtil.getTargetElseAttribute(typeName));
            if (CollectionUtil.isNotEmpty(list)) {
                List<SpecialAttribute> subList = null;
                Map<String, Object> map = null;
                for (SpecialAttribute specialAttribute : list) {
                    map = getAttributeMap(specialAttribute);
                    map.put("sign", 1);
                    lists.add(map);
                    //扩展属性
                    subList = targetTypeMapper.findSpecialByTypeId(specialAttribute.getId());
                    if (CollectionUtil.isNotEmpty(subList)) {
                        for (SpecialAttribute attribute : subList) {
                            map = getAttributeMap(specialAttribute);
                            map.put("sign", 2);
                            lists.add(map);
                        }
                    }
                }
            }
            resultMap.put("commonList", lists);
            return ResultUtil.success("查询成功", resultMap);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<SpecialAttribute> list = targetTypeMapper.findSpecialByTypeId(typeId);
        PageInfo<SpecialAttribute> pageInfo = new PageInfo<>(list);
        if (null != pageInfo.getList() && !pageInfo.getList().isEmpty()) {
            List<Object> lists = new ArrayList<>();
            for (SpecialAttribute specialAttribute : pageInfo.getList()) {
                lists.add(getAttributeMap(specialAttribute));
            }
            resultMap.put("commonList", lists);
        } else {
            resultMap.put("commonList", new ArrayList<>());
        }
        resultMap.put("pageNum", pageInfo.getPageNum());
        resultMap.put("pageSize", pageInfo.getPageSize());
        resultMap.put("total", pageInfo.getTotal());
        resultMap.put("pageAll", pageInfo.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result addPostureAttribute(SpecialAdd specialAdd) {
        if (judgePostureName(specialAdd.getKey())) {
            return ResultUtil.error(500, specialAdd.getKey() + "字段名称是态势专有属性，请重新命名");
        }
        //判断字段名称是否重复
        if (ObjectUtil.isNotEmpty(
                postureAttributeService.lambdaQuery()
                .eq(PostureAttribute::getKeyValue, specialAdd.getKey()).one()
        )) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
        }
        //判断属性名称是否重复
        if (ObjectUtil.isNotEmpty(postureAttributeService.lambdaQuery().eq(PostureAttribute::getTypeId,specialAdd.getTypeId()).eq(PostureAttribute::getKeyName, specialAdd.getKeyName()).one())) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
        }
        PostureAttribute postureAttribute = new PostureAttribute();
        BeanUtil.copyProperties(specialAdd, postureAttribute);
        Integer maxSort = postureAttributeService.getAttributeMaxSort(specialAdd.getTypeId());
        if (null == maxSort) {
            maxSort = 0;
        }
        postureAttribute.setKeyValue(specialAdd.getKey());
        postureAttribute.setRowValue(specialAdd.getRow());
        postureAttribute.setSort(maxSort + 1);
        postureAttributeService.save(postureAttribute);
        return ResultUtil.success("新增成功", null);
    }

    @Override
    public Result delPostureAttribute(String id) {
        if (StringUtils.isBlank(id)) {
            return ResultUtil.error(ResultEnum.DELETE_EMPTY);
        }
        postureAttributeService.removeById(id);
        return ResultUtil.success("删除成功", null);
    }

    @Override
    public Result updatePostureAttribute(SpecialAdd specialAdd) {
        if (judgePostureName(specialAdd.getKey())) {
            return ResultUtil.error(500, specialAdd.getKey() + "字段名称是态势专有属性，不可更改");
        }
        //判断字段名称是否重复
        PostureAttribute one = postureAttributeService.lambdaQuery().eq(PostureAttribute::getKeyValue, specialAdd.getKey()).one();
        if (ObjectUtil.isNotEmpty(one) && !one.getId().equals(specialAdd.getId())) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_EXIST);
        }
        //判断属性名称是否重复
        one = postureAttributeService.lambdaQuery().eq(PostureAttribute::getTypeId,specialAdd.getTypeId()).eq(PostureAttribute::getKeyName, specialAdd.getKeyName()).one();
        if (ObjectUtil.isNotEmpty(one) && !one.getId().equals(specialAdd.getId())) {
            return ResultUtil.error(ResultEnum.COMMON_KEY_NAME_EXIST);
        }
        PostureAttribute postureAttribute = new PostureAttribute();
        BeanUtil.copyProperties(specialAdd, postureAttribute);
        postureAttribute.setKeyValue(specialAdd.getKey());
        postureAttribute.setRowValue(specialAdd.getRow());
        postureAttributeService.saveOrUpdate(postureAttribute);
        return ResultUtil.success("更新成功", null);
    }

    /**
     * 专有属性前端数据封装
     * @param specialAttribute
     * @return
     */
    private Map<String, Object> getAttributeMap(SpecialAttribute specialAttribute) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", specialAttribute.getId());
        map.put("keyName", specialAttribute.getKeyName());
        map.put("key", specialAttribute.getKey());
        map.put("keyType", specialAttribute.getKeyType());
        map.put("showType", specialAttribute.getShowType());
        map.put("required", specialAttribute.getRequired());
        map.put("info", specialAttribute.getInfo());
        map.put("dataRange", specialAttribute.getDataRange());
        map.put("enumerator", FileElseUtil.getStringTransitionList(specialAttribute.getEnumerator()));
        map.put("row", specialAttribute.getRow());
        map.put("message", specialAttribute.getMessage());
        map.put("min", specialAttribute.getMin());
        map.put("max", specialAttribute.getMax());
        map.put("verify", specialAttribute.getVerify());
        return map;
    }

    /**
     * 态势属性前端数据封装
     * @param postureAttribute
     * @return
     */
    private Map<String, Object> getPostureAttributeMap(PostureAttribute postureAttribute) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", postureAttribute.getId());
        map.put("keyName", postureAttribute.getKeyName());
        map.put("key", postureAttribute.getKeyValue());
        map.put("keyType", postureAttribute.getKeyType());
        map.put("showType", postureAttribute.getShowType());
        map.put("required", postureAttribute.getRequired());
        map.put("info", postureAttribute.getInfo());
        map.put("dataRange", postureAttribute.getDataRange());
        map.put("enumerator", FileElseUtil.getStringTransitionList(postureAttribute.getEnumerator()));
        map.put("row", postureAttribute.getRowValue());
        map.put("message", postureAttribute.getMessage());
        map.put("min", postureAttribute.getMin());
        map.put("max", postureAttribute.getMax());
        map.put("verify", postureAttribute.getVerify());
        return map;
    }

    @Override
    public Result selectPostureAttribute(Integer pageNum, Integer pageSize, String typeId) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(typeId)) {
            resultMap.put("commonList", new ArrayList<>());
            return ResultUtil.success("查询成功", resultMap);
        }
        typeId = TargetUtil.getParamListOrString(typeId);
        if (pageNum == null || pageSize == null) {

            List<PostureAttribute> list = postureAttributeService
                    .lambdaQuery()
                    .eq(PostureAttribute::getTypeId, typeId)
                    .orderByAsc(PostureAttribute::getSort)
                    .list();
            List<Map<String, Object>> lists = new ArrayList<>();
            postureSpecial(lists);
            if (CollectionUtil.isNotEmpty(list)) {
                List<SpecialAttribute> subList = null;
                Map<String, Object> map = null;
                for (PostureAttribute postureAttribute : list) {
                    map = getPostureAttributeMap(postureAttribute);
                    lists.add(map);
                }
            }
            resultMap.put("commonList", lists);
            return ResultUtil.success("查询成功", resultMap);
        }
        Page<PostureAttribute> page = new Page(pageNum, pageSize);
        Page<PostureAttribute> postureAttributePage = postureAttributeService.lambdaQuery()
                .eq(PostureAttribute::getTypeId, typeId)
                .orderByAsc(PostureAttribute::getSort)
                .page(page);
        if (CollectionUtil.isNotEmpty(postureAttributePage.getRecords())) {
            List<Object> lists = new ArrayList<>();
            Map<String, Object> map = null;
            for (PostureAttribute postureAttribute : postureAttributePage.getRecords()) {
                map = getPostureAttributeMap(postureAttribute);
                lists.add(map);
            }
            resultMap.put("commonList", lists);
        } else {
            resultMap.put("commonList", new ArrayList<>());
        }
        resultMap.put("pageNum", postureAttributePage.getCurrent());
        resultMap.put("pageSize", postureAttributePage.getSize());
        resultMap.put("total", postureAttributePage.getTotal());
        resultMap.put("pageAll", postureAttributePage.getPages());
        return ResultUtil.success("查询成功", resultMap);
    }

    @Override
    public Result selectTypePullDown(String targetId, String isSub) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (StringUtils.isBlank(targetId)) {
            List<TargetType> list = targetTypeMapper.findAll();
            if (CollectionUtil.isNotEmpty(list)) {
                Map<String, Object> map;
                for (TargetType targetType : list) {
                    if (targetType.getLevel().equals("1")) {
                        map = new HashMap<>();
                        map.put("value", targetType.getTypeId());
                        map.put("label", targetType.getTypeName());
                        List<Map<String, Object>> child = getTreePullChild(targetType.getTypeId(), list);
                        if (CollectionUtil.isNotEmpty(child)) {
                            map.put("children", child);
                        }
                        resultList.add(map);
                    }
                }
            }
        } else {
            Target target = targetMapper.findById(targetId);
            List<TargetSubType> list = targetSubTypeMapper
                    .selectList(new LambdaQueryWrapper<TargetSubType>()
                    .eq(TargetSubType::getParentId, target.getType()));
            if (CollectionUtil.isNotEmpty(list)) {
                Map<String, Object> map;
                for (TargetSubType targetSubType : list) {
                    map = new HashMap<>();
                    map.put("value", targetSubType.getTypeId());
                    map.put("label", targetSubType.getTypeName());
//                    map.put("children", new ArrayList<>());
                    resultList.add(map);
                }
            }
        }
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    public Result selectPosturePullDown() {
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<PostureType> list = postureTypeService.list();
        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, Object> map;
            for (PostureType postureType : list) {
                if (postureType.getLevel().equals("1")) {
                    map = new HashMap<>();
                    map.put("value", postureType.getTypeId());
                    map.put("label", postureType.getTypeName());
                    List<Map<String, Object>> child = getPostureTreePullChild(postureType.getTypeId(), list);
                    if (CollectionUtil.isNotEmpty(child)) {
                        map.put("children", child);
                    }
                    resultList.add(map);
                }
            }
        }
        return ResultUtil.success("查询成功", resultList);
    }

    @Override
    public Result selectTypePull(String paranId) {
        if (StringUtils.isBlank(paranId)) {
            paranId = "1";
        }
        List<TargetType> list = targetTypeMapper.findTargetTypeByParantId(paranId);
        if (CollectionUtil.isNotEmpty(list)) {
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (TargetType targetType : list) {
                Map<String, Object> parent = new HashMap<>();
                parent.put("value", targetType.getTypeId());
                parent.put("label", targetType.getTypeName());
                resultList.add(parent);
            }
            return ResultUtil.success("查询成功", resultList);
        }
        return ResultUtil.success("查询成功", new ArrayList<>());
    }

    @Override
    public Result moveSpecialAttribute(String typeId, String type) {
        TargetType targetType = targetTypeMapper.selectTypeOnly(typeId);
        if (null == targetType) {
            return ResultUtil.error(404, "类型不存在/已被删除");
        }
        if (targetType.getParentId().equals("0")) {
            return ResultUtil.error(500, "根目录不能移动");
        }
        TargetType changeType;
        if ("up".equals(type)) {
            changeType = targetTypeMapper.selectUpTargetType(typeId, targetType.getParentId());
            if (null == changeType) {
                return ResultUtil.error(500, "已经到顶了，不能上移了。");
            }
            targetTypeMapper.updateTypeSort(targetType.getTypeId(), changeType.getSort());
            targetTypeMapper.updateTypeSort(changeType.getTypeId(), targetType.getSort());
            return ResultUtil.success(null);
        } else if ("down".equals(type)) {
            changeType = targetTypeMapper.selectDownTargetType(typeId, targetType.getParentId());
            if (null == changeType) {
                return ResultUtil.error(500, "已经置底了，不能下移了。");
            }
            targetTypeMapper.updateTypeSort(targetType.getTypeId(), changeType.getSort());
            targetTypeMapper.updateTypeSort(changeType.getTypeId(), targetType.getSort());
            return ResultUtil.success(null);
        }
        return ResultUtil.error(ResultEnum.STATUS_EMPTY);
    }

    @Override
    public Result getSpecialSort(String id, int sign) {
        SpecialAttribute special = targetTypeMapper.findSpecialById(id);
        if (null != special) {
            Map<String, Object> map = null;
            switch (sign) {
                case 1:
                    map = targetTypeMapper.getMin(special.getTypeId());
                    if (null == map || map.get("id").equals(special.getId())) {
                        return ResultUtil.error(500, "已经上移到最顶");
                    } else {
                        targetTypeMapper.updateSpecialSort(special.getId(), 1);
                        int count = 2;
                        List<String> list = targetTypeMapper.findSpecialSort(special.getTypeId());
                        for (String str : list) {
                            if (str.equals(special.getId())) {
                                continue;
                            }
                            targetTypeMapper.updateSpecialSort(str, count);
                            count++;
                        }
                    }
                    break;
                case 2:
                    map = targetTypeMapper.getUp(special.getSort(), special.getTypeId());
                    if (null == map || map.get("id").toString().equals(special.getId())) {
                        return ResultUtil.error(500, "已经上移到最顶");
                    } else {
                        targetTypeMapper.updateSpecialSort(special.getId(), (Integer) map.get("sort"));
                        targetTypeMapper.updateSpecialSort(map.get("id").toString(), special.getSort());
                    }
                    break;
                case 3:
                    map = targetTypeMapper.getDown(special.getSort(), special.getTypeId());
                    if (null == map) {
                        return ResultUtil.error(500, "已经下移到最底");
                    } else {
                        targetTypeMapper.updateSpecialSort(special.getId(), (Integer) map.get("sort"));
                        targetTypeMapper.updateSpecialSort(map.get("id").toString(), special.getSort());
                    }
                    break;
                case 4:
                    map = targetTypeMapper.getMax(special.getTypeId());
                    if (null == map || map.get("id").equals(special.getId())) {
                        return ResultUtil.error(500, "已经下移到最底");
                    } else {
                        targetTypeMapper.updateSpecialSort(special.getId(), targetTypeMapper.getSpecialMaxSort(special.getTypeId()) + 1);
                    }
                    break;
                default:
                    break;
            }
            return ResultUtil.success("操作成功", null);
        }
        return ResultUtil.error(ResultEnum.TYPE_EMPTY);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public synchronized Result getPostureSort(String id, int sign) {
        PostureAttribute postureAttribute = postureAttributeService.getById(id);
        if (ObjectUtil.isNotNull(postureAttribute)) {
            if (sign == 1 || sign == 2) {
                if (postureAttribute.getSort() == 1) {
                    return ResultUtil.error(500, "已经上移到最顶");
                } else if (sign == 1) {
                    postureAttributeService.updateSortBetweenAdd(postureAttribute.getTypeId(), 1, postureAttribute.getSort() - 1);
                    postureAttribute.setSort(1);
                    postureAttributeService.updateById(postureAttribute);
                } else {
                    postureAttributeService.updateSortBetweenAdd(postureAttribute.getTypeId(), postureAttribute.getSort() - 1, postureAttribute.getSort() - 1);
                    postureAttribute.setSort(postureAttribute.getSort() - 1);
                    postureAttributeService.updateById(postureAttribute);
                }
                return ResultUtil.success("操作成功", null);
            } else {
                Integer maxSort = postureAttributeService.getAttributeMaxSort(postureAttribute.getTypeId());
                if (null != maxSort && maxSort.intValue() == postureAttribute.getSort()) {
                    return ResultUtil.error(500, "已经下移到最底");
                } else if (sign == 3) {
                    postureAttributeService.updateSortBetweenSub(postureAttribute.getTypeId(), postureAttribute.getSort() + 1, postureAttribute.getSort() + 1);
                    postureAttribute.setSort(postureAttribute.getSort() + 1);
                    postureAttributeService.updateById(postureAttribute);
                } else {
                    postureAttributeService.updateSortBetweenSub(postureAttribute.getTypeId(), postureAttribute.getSort() + 1, maxSort);
                    postureAttribute.setSort(maxSort);
                    postureAttributeService.updateById(postureAttribute);
                }
                return ResultUtil.success("操作成功", null);
            }
        }
        return ResultUtil.error(ResultEnum.TYPE_EMPTY);
    }

    /**
     * 递归查询子节点目标树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getTreeChild(String id, List<TargetType> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", targetType.getTypeId());
                map.put("typeName", targetType.getTypeName());
                map.put("level", targetType.getLevel());
                map.put("hiden", false);
                map.put("url", StringUtils.isNotBlank(targetType.getUrl()) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + targetType.getUrl() : null);
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("typeId");
            map.put("children", getTreeChild(typeId, allTree));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    private List<Map<String, Object>> getTargetAndSubTree(String id, List<TargetType> allTree, List<TargetSubType> subList) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", targetType.getTypeId());
                map.put("typeName", targetType.getTypeName());
                map.put("level", targetType.getLevel());
                map.put("hiden", false);
                map.put("url", StringUtils.isNotBlank(targetType.getUrl()) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + targetType.getUrl() : null);
                childList.add(map);
            }
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("typeId");
            List<Map<String, Object>> subTree = getTargetAndSubTree(typeId, allTree, subList);
            for (TargetSubType targetSubType : subList) {
                if (targetSubType.getParentId().equals(typeId)) {
                    Map<String, Object> sub = new HashMap<>();
                    sub.put("typeId", targetSubType.getTypeId());
                    sub.put("typeName", targetSubType.getTypeName());
                    sub.put("level", (FileElseUtil.getObjectToInt(map.get("level"))  + 1) + "");
                    sub.put("hiden", false);
                    sub.put("url", null);
                    subTree.add(sub);
                }
            }
            map.put("children", subTree);
        }
        return childList;
    }

    /**
     * 递归查询子节点目标树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getPostureTreeChild(String id, List<PostureType> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (PostureType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", targetType.getTypeId());
                map.put("typeName", targetType.getTypeName());
                map.put("level", targetType.getLevel());
                map.put("hiden", false);
                map.put("url", StringUtils.isNotBlank(targetType.getUrl()) ? this.keyWordSystem.getSERVER_URL() + "/sign/" + targetType.getUrl() : null);
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("typeId");
            map.put("children", getPostureTreeChild(typeId, allTree));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 递归查询子节点目标树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getTreePullChild(String id, List<TargetType> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", targetType.getTypeId());
                map.put("label", targetType.getTypeName());
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("value");
            map.put("children", getTreePullChild(typeId, allTree));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 递归查询态势节点目标树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getPostureTreePullChild(String id, List<PostureType> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (PostureType postureType : allTree) {
            if (id.equals(postureType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", postureType.getTypeId());
                map.put("label", postureType.getTypeName());
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("value");
            map.put("children", getPostureTreePullChild(typeId, allTree));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 递归查询子节点目标树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getTreeChild(String id, List<TargetType> allTree, List<String> typeList) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("typeId", targetType.getTypeId());
                map.put("typeName", targetType.getTypeName());
                map.put("level", targetType.getLevel());
                map.put("hiden", false);
                if (CollectionUtil.isNotEmpty(typeList)) {
                    for (String s : typeList) {
                        if (targetType.getTypeId().equals(s)) {
                            map.put("hiden", true);
                            typeList.remove(s);
                            break;
                        }
                    }
                }
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("typeId");
            map.put("children", getTreeChild(typeId, allTree, typeList));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 递归查询下拉子节点目标树
     *
     * @param id
     * @param allTree
     * @return
     */
    private List<Map<String, Object>> getPullTreeChild(String id, List<TargetType> allTree) {
        /**
         * 子菜单
         */
        List<Map<String, Object>> childList = new ArrayList<>();
        for (TargetType targetType : allTree) {
            if (id.equals(targetType.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("value", targetType.getTypeId());
                map.put("label", targetType.getTypeName());
                childList.add(map);
            }
        }
        /**
         * 递归
         */
        for (Map<String, Object> map : childList) {
            String typeId = (String) map.get("value");
            map.put("children", getPullTreeChild(typeId, allTree));
        }
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    private boolean judgeParamName(String name) {
        String[] strs = {"targetName", "targetClassify", "country", "lon", "lat",
                "height", "subName", "shape", "length", "width", "radius",
                "innerRadius", "outRadius", "angle", "earthHeight", "lenghts", "icon",
                "mbRadioValue", "mbRadioType","postureType"};
        for (String str : strs) {
            if (name.toLowerCase().equals(str)) {
                return true;
            }
        }
        return false;
    }

    private boolean judgePostureName(String name) {
        String[] strs = {"icon","newimageUrl","targetName","targetClassify","position","score","riskLevel","amount","plotinfoobj"};
        for (String str : strs) {
            if (name.trim().toLowerCase().equals(str)) {
                return true;
            }
        }
        return false;
    }

    private void postureSpecial(List<Map<String, Object>> list) {
        {
            Map<String, Object> map = new HashMap<>();
            map.put("id", "100001");
            map.put("keyName", "态势类型");
            map.put("key", "postureType");
            map.put("keyType", "list");
            map.put("showType", "select");
            map.put("required", "false");
            map.put("info", "false");
            map.put("dataRange", "");
            map.put("verify", "false");
            map.put("min", "");
            map.put("max", "");
            List<Map<String, String>> resultList = new ArrayList<>();
            Map<String, String> m1 = new HashMap<>();
            m1.put("label", "进攻类型");
            m1.put("value", "进攻类型");
            resultList.add(m1);
            Map<String, String> m2 = new HashMap<>();
            m2.put("label", "防御类型");
            m2.put("value", "防御类型");
            resultList.add(m2);
            map.put("enumerator", resultList);
            map.put("row", "");
            map.put("message", "");
            list.add(map);
        }
    }

}